from fastapi import APIRouter, HTTPException
from ..db import session_scope, Annotation
from ..schemas import AnnotationIn

router = APIRouter(prefix="/texts", tags=["annotations"])

@router.get("/{doc_id}/annotations")
def list_annotations(doc_id: str):
    with session_scope() as s:
        rows = s.query(Annotation).filter(Annotation.doc_id == doc_id).all()
        data = [
            {
                "id": str(a.id),
                "doc_id": str(a.doc_id),
                "label_id": str(a.label_id),
                "start_offset": a.start_offset,
                "end_offset": a.end_offset,
                "text": a.text,
            }
            for a in rows
        ]
        return {"code": 0, "message": "ok", "data": data}

@router.post("/{doc_id}/annotations")
def create_annotation(doc_id: str, body: AnnotationIn):
    with session_scope() as s:
        item = Annotation(
            doc_id=body.doc_id,
            label_id=body.label_id,
            start_offset=body.start_offset,
            end_offset=body.end_offset,
            text=body.text,
        )
        s.add(item)
        s.flush()
        return {"code": 0, "message": "ok", "data": {"id": str(item.id)}}

@router.delete("/annotations/{ann_id}")
def delete_annotation(ann_id: str):
    with session_scope() as s:
        item = s.get(Annotation, ann_id)
        if not item:
            raise HTTPException(status_code=404, detail="Annotation not found")
        s.delete(item)
        return {"code": 0, "message": "ok"}
